<template>
  <div class="app-container">
    <el-card>
      <avue-form v-model="form" :option="option" @submit="handleSubmit">
        <template #image>
          <SingleImageUpload v-model="form.image" />
        </template>
      </avue-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import { HouseModel } from "@/model/house-model";
import houseFormOption from "./avue-options";
import HouseAPI from "@/api/house";

defineOptions({
  name: "HouseAdd",
});

const route = useRoute();
const loading = ref(false);

// 监听userId变化，重新获取数据
watch(
  () => route.query,
  async () => fetchData(),
  {
    immediate: true,
    deep: true,
  }
);

/// 表单数据
const form = ref<HouseModel>({
  id: undefined,
  name: "",
  image: "",
  room: undefined,
});
const option = ref<Object>(houseFormOption);

/**
 * @description 获取数据
 */
function fetchData() {
  const userId = route.query.id;
  if (!userId) {
    return;
  }

  loading.value = true;
  HouseAPI.detail(Number(userId))
    .then((res) => {
      form.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * @description 表单提交
 * @param form 表单数据
 * @param done 完成函数
 */
const handleSubmit = (form: any, done: Function) => {
  if (form.id) {
    handleEdit(form, done);
  } else {
    handleAdd(form, done);
  }
};

/**
 * @description 表单提交 添加
 * @param form 表单数据
 * @param done 完成函数
 */
function handleAdd(form: Object, done: Function) {
  HouseAPI.add(form)
    .then(() => {
      ElMessage.success("操作成功");
      router.back();
    })
    .finally(() => {
      done();
    });
}

/**
 * @description 表单提交 添加
 * @param form 表单数据
 * @param done 完成函数
 */
function handleEdit(form: Object, done: Function) {
  HouseAPI.edit(form)
    .then(() => {
      ElMessage.success("操作成功");
      router.back();
    })
    .finally(() => {
      done();
    });
}
</script>
